#include <stdio.h>
#include "driver/gpio.h"
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "esp_log.h"
#include "driver/ledc.h"  // 引入ledc库

#define LED_GPIO GPIO_NUM_13
#define LEDC_CHANNEL LEDC_CHANNEL_0  // 定义PWM通道
#define LEDC_TIMER LEDC_TIMER_0  // 定义PWM定时器
#define LEDC_DUTY_RES LEDC_TIMER_8_BIT  // 定义PWM分辨率
#define LEDC_DUTY_MAX 255  // 定义PWM最大占空比
#define LEDC_FREQUENCY 5000  // 定义PWM频率

#define LED_DELAY_MS 2000  // 修改: 将延时设置为1000毫秒，表示整个呼吸周期为1秒
#define LED_DELAY_RE 20  // 修改: 将LED_DELAY_RE设置为50，以减少每个亮度变化的延时
#define LED_EVERY_DELAY_RE (LED_DELAY_MS/LED_DELAY_RE/2)  // 修改: 计算每个亮度变化的步进延时

void blink_task(void *pvParameters)
{
    while (1)
    {
        // 闪烁
        for (int i = 0; i <= LED_DELAY_RE; i++)
        {
            int ddd = i * LEDC_DUTY_MAX / LED_DELAY_RE;
            ESP_LOGI("blink_task", "i = %d, duty=%d,%d,%d", i, ddd,LEDC_DUTY_MAX,LED_DELAY_RE);
            ledc_set_duty(LEDC_LOW_SPEED_MODE, LEDC_CHANNEL, ddd);
            ledc_update_duty(LEDC_LOW_SPEED_MODE, LEDC_CHANNEL);
            vTaskDelay(pdMS_TO_TICKS(LED_EVERY_DELAY_RE)); // 延时500ms
        }
        for (int i = LED_DELAY_RE; i >= 0; i--)
        {
            int ddd = i * LEDC_DUTY_MAX / LED_DELAY_RE;
            ESP_LOGI("blink_task", "i = %d, duty=%d,%d,%d", i, ddd,LEDC_DUTY_MAX,LED_DELAY_RE);
            ledc_set_duty(LEDC_LOW_SPEED_MODE, LEDC_CHANNEL, ddd);
            ledc_update_duty(LEDC_LOW_SPEED_MODE, LEDC_CHANNEL);
            vTaskDelay(pdMS_TO_TICKS(LED_EVERY_DELAY_RE)); // 延时500ms
        }
    }
}

void app_main(void)
{
    // 配置 GPIO 引脚为输出模式
    gpio_reset_pin(LED_GPIO);
    gpio_set_direction(LED_GPIO, GPIO_MODE_OUTPUT);

    // 配置 PWM 通道
    ledc_timer_config_t ledc_timer = {
        .speed_mode = LEDC_LOW_SPEED_MODE,
        .timer_num = LEDC_TIMER,
        .duty_resolution = LEDC_DUTY_RES,
        .freq_hz = LEDC_FREQUENCY,
        .clk_cfg = LEDC_AUTO_CLK,
    };
    ledc_timer_config(&ledc_timer);

    ledc_channel_config_t ledc_channel = {
        .speed_mode = LEDC_LOW_SPEED_MODE,
        .channel = LEDC_CHANNEL,
        .timer_sel = LEDC_TIMER,
        .intr_type = LEDC_INTR_DISABLE,
        .gpio_num = LED_GPIO,
        .duty = 0, // 初始占空比为0
        .hpoint = 0,
    };
    ledc_channel_config(&ledc_channel);

    // 创建并启动 blink_task，绑定到 CPU 核心 0
    xTaskCreatePinnedToCore(blink_task, "blink_task", 2048, NULL, 5, NULL, 1);
}
